<template>
  <el-dialog
    :visible.sync="visible"
    :before-close="beforeClose"
    :close-on-click-modal="false"
    append-to-body
    width="800px"
    top="30px"
    title="评级申请"
  >
    <div v-loading="loading">
      <div class="item-title text-primary py-2">评级有效期</div>
      <div class="d-flex align-items-center px-3">
        <div class="item-label font-weight-bold">评级期限</div>
        <div class="d-flex ml-3">
          <el-date-picker
            :clearable="false"
            style="width: 135px"
            v-model="masterData.year"
            class="mr-4"
            type="year"
            placeholder="年份"
            value-format="yyyy"
          ></el-date-picker>
          <c-select
            placeholder="选择季度"
            v-model="masterData.quarter"
            :options="enumQuarter"
          ></c-select>
        </div>
      </div>
      <div class="item-title text-primary py-3">评级指标情况录入</div>
      <div v-if="!listData.length">
        <div class="text-muted border rounded bg-light p-3 my-3">
          评级指标请求失败
          <el-button @click="getOptions" icon="el-icon-refresh">刷新</el-button>
        </div>
      </div>
      <div class="px-3">
        <div v-for="(p, index) of listData" :key="index">
          <div class="font-weight-bold">{{ p.label }}</div>
          <template v-if="p.children">
            <div
              class="d-flex py-1 align-items-center"
              v-for="(m, mindex) of p.children"
              :key="mindex"
            >
              <div class="item-label ml-3">
                <span class="text-danger">*</span>
                {{ m.label }}：
              </div>
              <div class="flex-1">
                <c-select
                  clearable
                  v-model="editData[`${index}-${mindex}`]"
                  class="form-control-ml"
                  :placeholder="`请选择${m.label}`"
                  :options="m.children"
                  :props="{ value: 'id', label: 'label' }"
                ></c-select>
              </div>
            </div>
          </template>
        </div>
      </div>

      <div class="item-title text-primary py-3">
        评级资料清单上传
        <small class="text-warning">(附件需提交后才会保存修改)</small>
      </div>
      <div>
        <ul class="list-unstyled attach-type-list">
          <li v-for="item in attathData" :key="item.tag" class="attach-type-item">
            <div class="attach-tag-label">
              <span class="text-danger mx-1" v-if="item.required">*</span>
              <span class="font-weight-bold">{{ item.tag }}</span>
            </div>
            <div>
              <input
                type="file"
                :ref="`up-${item.key}`"
                class="d-none"
                multiple
                accept="*"
                @change="e => handleFileChange(e, item.key)"
              />
              <el-button
                size="small"
                class="btn-long mb-1"
                icon="el-icon-upload2"
                @click="e => handleSelectFile(`up-${item.key}`)"
              >
                上传
              </el-button>
              <ul class="list-unstyled">
                <li
                  v-for="(file, index) in areadyFiles[item.key]"
                  :key="`aready-${index}`"
                  class="attach-item"
                >
                  <attach-item :attach-data="file"></attach-item>
                  <el-button
                    type="text"
                    class="text-danger"
                    @click="handleDeleteFile(1, index, item.key)"
                  >
                    删除
                  </el-button>
                </li>
              </ul>
              <div v-for="(file, index) in attachs[item.key]" :key="`attach-${index}`">
                <div class="d-flex align-items-center">
                  <i class="fa fa-fw text-muted mr-2 d-print-none" :class="file.viewIcon"></i>
                  <div>{{ file.name }}</div>
                  <el-button
                    class="ml-5 text-danger"
                    type="text"
                    :disabled="saveLoading"
                    @click="handleDeleteFile(2, index, item.key)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="item-title text-primary py-3">其他备注说明</div>
      <div class="d-flex align-items-center mx-3">
        <div class="item-label font-weight-bold"></div>
        <div class="d-flex ml-3 flex-1">
          <el-input
            v-model="masterData.remark"
            type="textarea"
            placeholder="其他备注说明"
            class="form-control-ml"
            :rows="5"
          ></el-input>
        </div>
      </div>
      <div v-if="listData.length" class="d-flex m-5">
        <div class="item-label font-weight-bold"></div>
        <div>
          <el-button class="btn-long" type="primary" @click="submit" :loading="saveLoading">
            提交
          </el-button>
          <el-button class="btn-long" @click="beforeClose">取消</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import AttachItem from '@/bank/components/attach/Item'
import { service } from '@vimi/utils-api'
import { cascaderParse, cascaderFindAll } from '@vimi/utils-tool'
import { uploadOss, deleteOss } from '@/common/api/oss'
import { arrayFromString, arrayToString } from '@vimi/utils-tool'
export const enumQuarter = {
  1: '第一季度',
  2: '第二季度',
  3: '第三季度',
  4: '第四季度',
}
export default {
  components: {
    AttachItem,
  },
  props: {
    tableId: String,
    visible: Boolean,
  },
  data() {
    return {
      loading: false,
      listData: [],
      enumQuarter,
      editData: {},
      masterId: {},
      masterData: {},
      attathData: [
        {
          tag: '营业执照',
          key: 'register_no_attachment',
          // required: true,
        },
        // {
        //   tag: '其他附件',
        //   key: 'other',
        // },
      ],
      attachs: {
        // other: [],
        register_no_attachment: [],
      },
      areadyFiles: {
        // other: [],
        register_no_attachment: [],
      },
      saveLoading: false,
      tableName: 'agency_rating',
      params: {},
      deleteFiles: [],
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user']),
  },
  watch: {
    tableId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {
    this.getOptions()
  },
  mounted() {},
  methods: {
    getData() {
      const date = new Date()
      this.editData = {}
      this.masterData = {
        year: `${date.getFullYear()}`,
        quarter: `${Math.ceil((date.getMonth() + 1) / 3)}`,
      }
      this.masterId = {}
      if (!this.tableId) {
        this.initForm({})
        return
      }
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, {
          'agency_rating_id.eq': this.tableId,
          subKey: 'agency_rating_quota.agency_rating_id',
        })
        .then(res => {
          const data = res?.data?.[0] || {}
          const quotas = data.agency_rating_quota ?? []
          quotas.forEach(item => {
            this.editData[item.order_num] = item.third_quota_id
            this.masterId[item.order_num] = item.id
          })
          this.masterData = {
            year: data.year,
            quarter: data.quarter,
            remark: data.remark,
            agency_rating_id: data.agency_rating_id,
          }
          this.initForm(data)
        })
        .finally(() => {
          this.loading = false
        })
    },
    getOptions() {
      this.loading = true
      service
        .post(`/api/credit/proxy/`, {
          proxy_key: 'norm-config-query',
          params: JSON.stringify({ parent_id: '' }),
        })
        .then(res => {
          const data = res?.data?.auto_data?.gradeNormList || []
          this.listData = cascaderParse({
            data: data,
            key: 'id',
            parentKey: 'parent_id',
            checkParent: true,
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    validator() {
      const objectVaidator = {
        year: '请选择年限',
        quarter: '请选择季度',
      }
      for (const key in objectVaidator) {
        if (!this.masterData[key]) {
          this.$message.warning(objectVaidator[key])
          return false
        }
      }
      for (let index = 0; index < this.listData.length; index++) {
        for (let mIndex = 0; mIndex < this.listData[index].children.length; mIndex++) {
          if (!this.editData[`${index}-${mIndex}`]) {
            this.$message.warning(`请选择${this.listData[index].children[mIndex].label}`)
            return false
          }
        }
      }
      return true
    },
    async submit() {
      const data = []
      if (!this.validator()) {
        return
      }
      Object.keys(this.editData).forEach(key => {
        const item = cascaderFindAll(this.listData, item => item.id === this.editData[key])
        if (item.length === 3) {
          const dataItem = {
            order_num: key,
            first_quota_code: item[0].value,
            first_quota_name: item[0].label,
            second_quota_code: item[1].value,
            second_quota_name: item[1].label,
            third_quota_code: item[2].value,
            third_quota_id: item[2].id,
            third_quota_name: item[2].label,
          }
          if (this.masterId[key]) {
            dataItem.id = this.masterId[key]
          }
          if (this.masterData.agency_rating_id) {
            dataItem.agency_rating_id = this.masterData.agency_rating_id
          }
          data.push(dataItem)
        }
      })
      for (let key of Object.keys(this.attachs)) {
        const uploadData = {}
        uploadData[key] = this.attachs[key].map(it =>
          uploadOss({
            file: it.file,
            dir: `credit/grade/${this.clientId}`,
            type: 0,
            progress: ({ percent }) => {
              it.percent = percent
              it.loading = percent < 100
            },
          })
        )
        this.masterData[key] = await Promise.all(uploadData[key]).then(list => {
          return arrayToString([...this.areadyFiles[key].map(it => it.url), ...list])
        })
      }
      this.masterData.agency_id = this.clientId
      this.masterData.submit_person_name = this.user.realName
      const formData = {
        masterTableInfo: JSON.stringify(this.masterData),
        masterTableName: 'agency_rating',
        slaveTableInfo: JSON.stringify(data),
        slaveTableName: 'agency_rating_quota',
      }
      this.saveLoading = true
      if (!this.masterData.agency_rating_id) {
        this.$api
          .relatedBatch(this.$serviceName, formData)
          .then(() => {
            this.getData()
            this.$emit('success', true)
            this.$message.success('保存成功！')
            this.deleteOssFiles()
            this.beforeClose()
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || `保存失败，请重试！`)
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.$api
          .relatedUpdate(this.$serviceName, formData)
          .then(() => {
            this.getData()
            this.$emit('success', true)
            this.$message.success('保存成功！')
            this.deleteOssFiles()
            this.beforeClose()
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || `保存失败，请重试！`)
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    initForm(data) {
      Object.keys(this.areadyFiles).forEach(key => {
        const item = arrayFromString(data[key])
        this.areadyFiles[key] = item.reduce((prev, curr) => {
          prev.push({
            url: curr,
            ...attachAdapter({ attachment: curr }),
          })
          return prev
        }, [])
      })
    },
    deleteOssFiles() {
      if (!this.deleteFiles.length) return
      deleteOss(this.deleteFiles.map(it => it.url))
    },
    handleSelectFile(upkey) {
      const uploadInput = this.$refs[upkey]
      uploadInput[0].click()
    },
    handleFileChange(e, key) {
      const { files = [] } = e.target
      if (!this.attachs[key]) {
        this.attachs[key] = []
      }
      for (let i = 0; i < files.length; i++) {
        this.attachs[key].push(fileAdapter(files[i]))
      }
      this.resetInput(key)
    },
    handleDeleteFile(type, index, key) {
      if (type === 2) {
        const file = this.attachs[key][index]
        revokeObjectURL(file.url)
        this.attachs[key].splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles[key].splice(index, 1))
      }
    },
    resetInput(key) {
      const uploadInput = this.$refs[`up-${key}`]
      if (uploadInput) {
        uploadInput[0].value = ''
      }
    },
    handleAttachSuccess() {
      // console.log(val)
    },
    beforeClose() {
      Object.keys(this.attachs).forEach(key => {
        this.attachs[key] = []
      })
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style lang="scss" scoped>
.item-title {
  font-size: 1.1rem;
}
.item-label {
  width: 130px;
}
.attach-label {
  width: 250px;
}
.attach-type-list > .attach-type-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.attach-type-item {
  display: flex;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px dotted $gray-200;
}

.attach-tag-label {
  width: 180px;
  width: var(--tag-balel-width, 180px);
  padding-top: 0.25rem;
  padding-left: 0.5rem;
}
.attach-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(128, 128, 128, 0.1);
}

.list-unstyled .attach-item:last-child {
  border-bottom: none;
}
</style>
